package plugins.iTw3et;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;

public class OAuthTwitterClient {

    private final static String consumerKey = "Wajm4xOUbeB52k89CrCQ";
    private final static String consumerSecret = "cKbpBRSUTr2YQFiZo7zeC6U6cnE9xywznAkAfejg";
    private final static String tokenFile = "iTw3etToken.txt";
    Properties OauthLoginProps = new Properties();

    /**
     * Constructor to load properties from property file
     */
     public OAuthTwitterClient() {
    	 //Properties prop = new Properties();
    	 //Properties OauthLoginProps1 = new Properties();
     	try {
                //load a properties file
     		OauthLoginProps.load(new FileInputStream("plugins/iTw3et/OauthLogin.properties"));	  
     	} catch (IOException ex) {
     		System.out.println(ex.toString());
         }
    }
    
    public String updateStatus(String status) throws TwitterException,
            IOException {

        /**
         * Read properties file.
         */
        
        try {
            FileInputStream in = new FileInputStream("plugins/iTw3et/OauthLogin.properties");
            OauthLoginProps.load(in);
            in.close();
        } catch (IOException oauthPropsNotLoaded) {
        }



        /**
         * @param UserID - The Twitter UserID
         */
        Boolean UidExists = OauthLoginProps.containsKey("TweetUserID");

        /**
         * Removing the Twitter UID tokens as properties
         */
        OauthLoginProps.remove("TweetUserID");
        OauthLoginProps.remove("TweetToken");
        OauthLoginProps.remove("TweetTokenSecret");

        Twitter twitter = new Twitter();
        twitter.setOAuthConsumer(consumerKey, consumerSecret);
        RequestToken requestToken = twitter.getOAuthRequestToken();
        AccessToken accessToken = null;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (accessToken == null) {
            System.out.println("Open the following URL and grant access to your account:");
            System.out.println(requestToken.getAuthorizationURL());
            // Copy the authorization URL in your browser
            // http://twitter.com/oauth/authorize?oauth_token=r9YJ8P1gZJVzmb8Y6pYSsosUYe2o8MRCchuFVrspoRU
            // Log in Twitter, grant access
            // Get a PIN returned, e.g., 738805
            // Notice you can use HttpClient to do the job above
            System.out.println("Copy the PIN displayed in your browser, then hit ENTER: ");
            String pin = br.readLine();
            accessToken = twitter.getOAuthAccessToken(requestToken, pin);            
        	}

        // Persist the access token for future reference
        int userId = twitter.verifyCredentials().getId();
        storeAccessToken(userId, accessToken);
        try {
            Status twitterStatus = twitter.updateStatus(status);
            System.out.println("Successfully updated the status for user with ID " + userId + " to [" + twitterStatus.getText() + "].");
            return twitterStatus.getText();
        } catch (TwitterException notUpdated) {
            return notUpdated.toString();

        }
    }

    public String updateStatus(int userId, String status)
            throws TwitterException, IOException {
        Twitter twitter = new Twitter();
        twitter.setOAuthConsumer(consumerKey, consumerSecret);
        AccessToken accessToken = loadAccessToken(userId);
        twitter.setOAuthAccessToken(accessToken);
        try{
            Status twitterStatus = twitter.updateStatus(status);
            System.out.println("Successfully updated the status for user with ID "+ userId + " to [" + twitterStatus.getText() + "].");
            return twitterStatus.getText();
        }
        catch (TwitterException notUpdated){
            return notUpdated.toString();

        }

        
    }

    private void storeAccessToken(int userId, AccessToken accessToken)
            throws IOException {
        // Store user ID, token and token secret
        System.out.println("Storing access token for " + userId + "...");
        	/*
        	 * Check if the Property File Already exists if not create 
        	 */
        	File oauthCreds = new File(tokenFile);
        	if(!oauthCreds.exists()) 
        	{ 
        	  try 
        	  { 
        	    // Try creating the file 
        		  oauthCreds.createNewFile(); 
        	  } 
        	  catch(IOException NoFileExists) 
        	  { 
        		  System.out.print("Credentials File Missing. Not able to create file, see Error Message : " + NoFileExists.toString());
        	  } 
        	}
	        BufferedWriter out = new BufferedWriter(new FileWriter(tokenFile));
	        out.append("" + userId);
	        out.append(" ");
	        out.append(accessToken.getToken());
	        out.append(" ");
	        out.append(accessToken.getTokenSecret());
	        out.newLine();

	        /**
	         * Setting the Twitter UID tokens as properties
	         */
	        OauthLoginProps.setProperty("TweetUserID", Integer.toString(userId));
	        OauthLoginProps.setProperty("TweetToken",accessToken.getToken());
        	OauthLoginProps.setProperty("TweetTokenSecret", accessToken.getTokenSecret());
        /**
         * Saving properties file.
         */
        try {
        	
            FileOutputStream writePropToFile = new FileOutputStream("plugins/iTw3et/OauthLogin.properties");
            OauthLoginProps.store(writePropToFile, "---OAuth Parameters---");
            writePropToFile.close();

        } catch (IOException e) {
        }
        out.close();
        System.out.println("Done");
    }

    private AccessToken loadAccessToken(int userId) throws IOException {
        AccessToken accessToken = null;
        accessToken = new AccessToken(OauthLoginProps.getProperty("TweetToken"), OauthLoginProps.getProperty("TweetTokenSecret"));
        return accessToken;
    }  
    
/*
 * load properties from XML file

import java.io.FileInputStream;
import java.util.Properties;

public class LoadXmlProperties {
    public static void main(String[] args) {
        LoadXmlProperties lxp = new LoadXmlProperties();
        try {
            Properties properties = lxp.readProperties();
            
              //Display all properties information
             
            properties.list(System.out);

            
             // Read the value of data.folder and jdbc.url configuration
             
            String dataFolder = properties.getProperty("data.folder");
            System.out.println("dataFolder = " + dataFolder);
            String jdbcUrl = properties.getProperty("jdbc.url");
            System.out.println("jdbcUrl = " + jdbcUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Properties readProperties() throws Exception {
        Properties properties = new Properties();
        FileInputStream fis = new FileInputStream("configuration.xml");
        properties.loadFromXML(fis);

        return properties;
    }
}
 */
}